package com.kelai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kelai.service.IWeChatService;
import com.kelai.utils.WeXinUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Objects;

/**
 * 微信服务
 * Created by Luffy on 2017/8/6.
 */
@Service("weChatService")
public class DefaultWeChatService implements IWeChatService {

    private final static Logger logger = LoggerFactory.getLogger(DefaultWeChatService.class);

    /**
     * 发送模板消息
     * @param data
     * @throws IOException
     */
    @Override
    public void sendTemplate(String data) throws IOException {

        String token = WeXinUtil.getAccessToken();
        String requestUrl = WeXinUtil.MESSAGE_URL+"?access_token=" + token;

        InputStream is = new ByteArrayInputStream(data.getBytes("UTF-8"));
        InputStreamEntity entity = new InputStreamEntity(is, is.available());

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(requestUrl);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        try {
            HttpEntity resEntity = response.getEntity();
            InputStream resIs = resEntity.getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(resIs, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            resIs.close();
            JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
            if (Objects.equals(jsonObject.get("errcode").toString(), "40001")) {
                 WeXinUtil.TOKEN_CACHE_TOKEN_TIME = 0L;
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }

    }

}
